<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/6
 * Time: 9:27
 */

namespace app\api\controller\user;

use app\api\controller\HomeCommon;
use app\api\model\Config;
use app\api\model\MoneyCard;
use app\api\model\Product;
use app\api\model\ProductInteractive;
use app\api\model\ProductOrderRelation;
use app\api\model\ProductSku;
use app\api\model\SendCode;
use app\api\model\UserDemand;
use app\api\model\UserEnterprise;
use app\api\model\UserFeedback;
use app\api\model\UserMoneyOrder;
use app\api\model\UserToken;
use app\common\controller\UtilCommon;
use app\lib\exception\FailedException;
use app\lib\exception\NotFoundException;
use app\lib\exception\ParameterException;
use app\lib\exception\TokenException;
use app\Validate\CreateEnterpriseValidate;
use app\Validate\CreateShopValidate;
use app\Validate\DemandValidate;
use app\Validate\FeedbackValidate;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use app\Validate\PhoneValidate;
use app\Validate\SourceValidate;
use Payment\Client\Charge;
use Payment\Common\PayException;
use think\Db;
use think\Request;


class User extends HomeCommon
{
    /**
     * 退出登录
     * @param Request $request
     * @return \think\response\Json
     * @throws TokenException
     */
    public function logOut(Request $request){
        $post = $request->post();
        $where = [
            ['token','eq',$post['token']],
            ['user_id','eq',$post['user_id']],
        ];
        $res = (new UserToken())->where($where)->setField("delete_time",time());
        if(!$res){
            throw  new TokenException(['msg'=>'退出登录失败']);
        }
        return writeJson(200,[],"退出登录成功");
    }

    /**
     * 用户更改电话号
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws ParameterException
     */
    public function userChangePhone(Request $request){
        (new PhoneValidate())->goCheck();
        $post = $request->post();
        if(!isset($post['oldPhone'])){
            throw new FailedException(['msg'=>['缺少老电话字段']]);
        }
        if(!isset($post['code'])){
            throw new FailedException(['msg'=>['缺少验证码']]);
        }
        if($post['oldPhone']==$post['phone']){
            throw new FailedException(['msg'=>'老电话与新电话一致']);
        }
        $count = (new \app\api\model\User())->getCount([['phone','eq',$post['phone']]]);
        if($count>0){
            throw new FailedException(['msg'=>'电话号已绑定']);
        }
        $where = [
            ['phone','eq',$post['phone']],
            ['code','eq',$post['code']],
            ['create_time','gt',time()-12000]
        ];
        $res =(new SendCode())->findOne($where);

        if($res){
            // 验证通过
            $update_where =[
              'id'=>$post['user_id'],
                'phone'=>$post['phone']
            ];
            $find_res = (new \app\api\model\User())->dataUpdate($update_where);
            Db::startTrans();
            if($find_res){
                Db::commit();
                return writeJson(200,[],'操作成功');
            }else{
                Db::rollback();
                throw new FailedException(['msg'=>'操作失败']);
            }
        }else{
            throw new FailedException(['msg'=>'验证码不正确']);
        }
    }

    /**
     * 查询用户信息模块
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function userInfo(Request $request){
        $post =  $request->post();
        $userInfo = (new \app\api\model\User())->findOne([['id','eq',$post['user_id']]],"id,phone,user_type,buy_card_number,trade_money,head_img,vip_time");
        $userInfo['head_img'] = imgUrlToAbsolute((new Config())->findOne([['k','eq','default_head_img']],'v'));
        $userInfo['no_pay'] = (new \app\api\model\ProductOrder())->getCount([['user_id','eq',$post['user_id']],['status','eq',0]]);
        $userInfo['no_send'] = (new \app\api\model\ProductOrder())->getCount([['user_id','eq',$post['user_id']],['status','eq',1]]);
        $userInfo['no_sure'] = (new \app\api\model\ProductOrder())->getCount([['user_id','eq',$post['user_id']],['status','eq',2]]);
        $userInfo['cancel'] = 0;
//        $userInfo['cancel'] = (new \app\api\model\ProductOrder())->getCount([['user_id','eq',$post['user_id']],['status','eq',4]]);
        $userInfo['return_detail'] = (new \app\api\model\ProductOrder())->getCount([['user_id','eq',$post['user_id']],['return_status','gt',1]]);
        //防止会员过期
        if($userInfo["vip_time"] < time()){
            $userInfo["user_type"] = 1;
        }
        return writeJson(200,$userInfo);
    }

    /**
     * 企业申请
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function userEnterpriseCreate(Request $request){
        (new CreateEnterpriseValidate())->goCheck();
        $post = $request->post();
        $user_type = (new \app\api\model\User())->findOne([['id','eq',$post['user_id']]],"user_type");
        if($user_type>2){
            return writeJson(200,'您已经是企业号身份','您已经是企业号身份',200);
        }
        $where = [
          ['user_id','eq',$post['user_id']],
          ['status','eq',1]
        ];
        $list =  (new UserEnterprise())->findOne($where);
        if($list){//大于2 表示已经是企业号身份 如果有list说明有
            throw  new FailedException(['msg'=>'您已提交企业号申请，等待后台审核']);
        }
        $new =[
          'user_id'=>$post['user_id'],
            'enterprise_person_name'=>$post['enterprise_person_name'],
            'contact_number'=>$post['contact_number'],
            'enterprise_name'=>$post['enterprise_name'],
            'hand_id_card'=>$post['hand_id_card'],
            'front_id_card'=>$post['front_id_card'],
            'back_id_card'=>$post['back_id_card'],
            'licence'=>$post['licence'],
        ];
        $res = (new UserEnterprise())->dataUpdate($new);
        if(!$res){
            throw  new FailedException(['msg'=>'申请失败']);
        }
        return writeJson(200,[],'申请成功');
    }

    /**
     * 意见反馈
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function userFeedback(Request $request){
        (new FeedbackValidate())->goCheck();
         $post =  $request->post();
         $new = [
           'contact_number'=>$post['contact_number'],
             'content'     =>$post['content'],
             'user_id'     =>$post['user_id']
         ];
         $res = (new UserFeedback())->dataUpdate($new);
        if(!$res){
            throw  new FailedException(['msg'=>'提交失败']);
        }
        return writeJson(200,[],'提交成功');
    }

    /**
     * 加载会员列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function userMoneyCard(Request $request){
        (new PageMustValidate())->goCheck();
        $post =  $request->post();
        $where =[];
        $where['page'] = $post['page'];
        $data = (new MoneyCard())->wechatListTotal($where,"id,price,give_day","sort desc");
        return writeJson(200,$data);
    }

    /**
     * 会员充值列表
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws ParameterException
     */
    public function userCreateMoneyCard(Request $request){
        (new IdMustPositive())->goCheck();
        (new SourceValidate())->goCheck();
        $post = $request->post();
        $card = (new MoneyCard())->findOne([['id','eq',$post['id']]]);
        if(!$card){
            throw new NotFoundException(['msg'=>'暂无此会员卡']);
        }
        $new = [
          'user_id'=>$post['user_id'],
            'order_number'=>(new UserMoneyOrder())->createOrderNumber("UMO"),
            'card_id' =>$post['id'],
            'pay_money'=>$card['price'],
            'give_day' =>$card['give_day'],
            'source'  =>$post['source'],
            'pay_style'=>$post['pay_style']
        ];
        if(TestPrice==1){
            $new['pay_money'] = 0.01;
        }
        $res = (new UserMoneyOrder())->dataUpdate($new);
        if($res){
            if($post['source']==1){ //如果是PC端
                if($post['pay_style']==1){ //微信支付
                    $orderInfo= [
                        'order_number'    => $new['order_number'],
                        'total_price'    => $new['pay_money'],// 单位为元 ,最小为0.01
                        'order_type'     => 2
                    ];
                    $notify = "https://api.globaltc.cn/api/notify/wxNotify";
                    $res = wxpay($orderInfo,$notify);
                    Db::commit();
                    return writeJson(200,['payInfo'=>$res,'order_number'=>$orderInfo['order_number'],'total_price'=>$orderInfo['total_price']]);
                }elseif($post['pay_style']==2){ //支付宝支付
                    try {
                        $config = require_once  ALI_PATH."webaliconfig.php";
                        $info = [
                            'body'    => '万享集',
                            'subject'    => '用户充值',
                            'order_no'    => $new['order_number'],
                            'timeout_express' => time() + 600,// 表示必须 600s 内付款
                            'amount'    => $new['pay_money'],// 单位为元 ,最小为0.01
                            'return_param' => '1_2',
                            'goods_type' => '0',// 0—虚拟类商品，1—实物类商品
                            'store_id' => '',
                            'qr_mod' => '',
                        ];
                        $res=  Charge::run("ali_web",$config,$info);
                        Db::commit();
                        return writeJson(200,['payInfo'=>$res]);
                    } catch (PayException $e) {
                        Db::rollback();
                        throw new FailedException(['msg'=>$e->errorMessage()]);
                    }
                }
            }elseif($post['source']==2){
                if($post['pay_style']==1){//微信支付
                    $config = require_once PAY_PATH . 'wxappconfig.php';
                    $payData = [
                        'body'    => '用户充值',
                        'subject'    => '用户充值',
                        'order_no'    => $new['order_number'],
                        'timeout_express' => time() + 600,// 表示必须 600s 内付款
                        'amount'    => $new['pay_money'],// 微信沙箱模式，需要金额固定为3.01
                        'return_param' => '2_2',
                        'client_ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',// 客户地址
                    ];
                    try {
                        $res=  Charge::run("wx_app",$config,$payData);
                        Db::commit();
                        return writeJson(200,['payInfo'=>$res,'payData'=>$payData]);
                    } catch (PayException $e) {
                        Db::rollback();
                        throw new FailedException(['msg'=>$e->errorMessage()]);
                    }
                }elseif($post['pay_style']==2){//支付宝支付
                    try {
                        $config = require_once  ALI_PATH."aliconfig.php";
                        $info = [
                            'body'=>'万享集',
                            'subject'=>'用户充值',
                            'order_no'=>$new['order_number'],
                            'amount' =>$new['pay_money'],
                            'return_param' => '2_2',
                        ];
//                        $config['notify_url'] = "https://api.globaltc.cn/api/notify/moneyAliNotify";
                        $res=  Charge::run("ali_app",$config,$info);
                        return writeJson(200,['payInfo'=>$res]);
                    } catch (PayException $e) {
                        throw new FailedException(['msg'=>$e->errorMessage()]);
                    }
                }
                return writeJson(200);
            }
        }
    }

    /**
     * 创建下单
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     * @throws FailedException
     */
    public function userCreateMoneyOrder(Request $request){
        (new IdMustPositive())->goCheck();
        $post =  $request->post();
        $card  = (new MoneyCard())->findOne([['id','eq',$post['id']]]);
        if(!$card){
            throw new NotFoundException(['msg'=>'会员卡不存在']);
        }
        $new = [
            'card_id'=>$post['id'],
            'user_id'=>$post['user_id'],
            'pay_money'=>$card['price'],
            'give_day' =>$card['give_day'],
            'order_number'=>(new UserMoneyOrder())->createOrderNumber("UMO")
        ];
        $res = (new UserMoneyOrder())->dataUpdate($new);
        if(!$res){
            throw  new FailedException(['msg'=>'操作失败']);
        }
        return writeJson(200,[],'等待支付接口');
    }

    /**
     * 发布需求时候查询产品的详情
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function productDetail(Request $request){
        (new IdMustPositive())->goCheck();
         $post =$request->post();
         $productDetail = (new Product())->findOne([['id','eq',$post['id']]],'id,product_name,img_path');
         if(!$productDetail){
             throw  new FailedException(['msg'=>'商品不存在']);
         }
         $productDetail = $productDetail->toArray();
         $productDetail['img_path'] = serializeMysql($productDetail['img_path'],1);
         foreach ($productDetail['img_path'] as $key=>$value){
             $productDetail['img_path'][$key] = imgUrlToAbsolute($value);
         }
         $where = [
             ['id','eq',$post['id']]
         ];
         $productSku = (new Product())->selectList($where,"id as product_id,sku_remark as sku_name");
         $productSku = $productSku->toArray();
         $returnData = [
           'productDetail'=>$productDetail,
           'productSku'   =>$productSku
         ];
         return writeJson(200,$returnData);
    }

    /**
     * 用户发布需求
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws ParameterException
     */
    public function productCreateDemand(Request $request){
        (new DemandValidate())->goCheck();
        $post =$request->post();
        if(!isset($post['purchase_data'])||!is_array($post['purchase_data'])){
            throw new FailedException(['msg'=>'请添加采购数量']);
        }
        foreach ($post['purchase_data'] as $value){
            if(!isset($value['sku_name'])){
                throw new ParameterException(['msg'=>'缺少SKU名称']);
            }
            if(!isset($value['number'])){
                throw new ParameterException(['msg'=>'缺少对应数量']);
            }
        }
        $new = [
            'user_id'=>$post['user_id'],
            'product_id'=>$post['product_id'],
            'linkman' =>$post['linkman'],
            'contact_number'=>$post['contact_number'],
            'address'=>$post['address'],
            'remark' =>$post['remark'],
            'purchase_data' =>serializeMysql($post['purchase_data'])
        ];
        $res = (new UserDemand())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'发布需求失败']);
        }
        return writeJson(200,[],"发布成功");
    }

    /**
     * 获取数量
     * @param Request $request
     * @return \think\response\Json
     * @throws ParameterException
     */
    public function userProductCollectStatus(Request $request){
        (new IdMustPositive())->goCheck();
        $post =$request->post();
        $where[] =[
            ['user_id','eq',$post['user_id']],
            ['type','eq',1],
            ['info_id','eq',$post['id']]
        ];
        $count = (new ProductInteractive())->getCount($where);
        return writeJson(200,['count'=>$count]);
    }

    /**
     * 收藏/取消收藏操作
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws ParameterException
     */
    public function userProductCollect(Request $request){
        (new IdMustPositive())->goCheck();

        $post =$request->post();
        if(!isset($post['source'])){
            throw new ParameterException(['msg'=>'缺少用户类型']);
        }
        $where[] =[
            ['user_id','eq',$post['user_id']],
            ['type','eq',1],
            ['info_id','eq',$post['id']]
        ];
        $count = (new ProductInteractive())->getCount($where);
        if($count>0){
            $res = (new ProductInteractive())->where($where)->delete();
            if(!$res){
                throw new FailedException(['msg'=>'取消收藏失败']);
            }
            return writeJson(200,[],"取消收藏成功");
        }else{
            $new = [
              'user_id'=>$post['user_id'],
              'type'   =>1,
              'info_id'=>$post['id'],
              'source' =>$post['source']
            ];
            $res =  (new ProductInteractive())->dataUpdate($new);
            if(!$res){
                throw new FailedException(['msg'=>'收藏失败']);
            }
            return writeJson(200,[],"收藏成功");
        }
    }

    /**
     * 获取用户收藏列表
     * @param Request $request
     * @return \think\response\Json
     * @throws ParameterException
     * @throws \think\exception\DbException
     */
    public function userCollectList(Request $request){
        (new PageMustValidate())->goCheck();
        $post =$request->post();
        $where = [
            ['a.user_id','eq',$post['user_id']],
            ['b.is_publish','eq',2],
            ['c.status','eq',2],
            ['c.use_status','eq',1]
        ];
        $field = "b.id,b.cover_img,b.product_name,c.type,d.price";
        $dataList = (new ProductInteractive())
            ->alias("a")
            ->join("om_product b","a.info_id = b.id","right")
            ->join("om_shop c","b.uid = c.id","right")
            ->join("om_product_price d","a.info_id = d.product_id and d.type =1 and d.delete_time is null","left")
            ->field($field)
            ->where($where)
            ->order('a.update_time desc')
            ->paginate($post['page_number'], false, [
                'page' => $post['page']]);
        $dataList=$dataList->toArray();
        $data = $dataList['data'];
        foreach ($data as $key=>$value){
            $data[$key]['cover_img'] = imgUrlToAbsolute($value['cover_img']);
            //增加hall_id字段，如果有则随机取一条，没有则为0
            $data[$key]['hall_id'] = 0;
            $hallModel = (new \app\api\model\TradeHall())->where([["product_id","eq",$value["id"]]])->limit(1)->find();
            if(isset($hallModel)){
                $data[$key]['hall_id'] = $hallModel["id"];
            }
        }
        $returnList = [
            'count'=>$dataList['total'],
            'data'=>$data
        ];
        return writeJson(200,$returnList);
    }

    /**
     * 我发布的需求列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function userDemand(Request $request){
        $post =$request->post();
        $where = [];
        $where[] = ['user_id','eq',$post['user_id']];
        $where['page'] = $post['page'];
        $dataList = (new UserDemand())->wechatListTotalWith("product",$where,"*","id desc",$post['page_number']);
        foreach ($dataList['data'] as &$value){
            $value['type'] =  (new Product())
                ->alias("a")
                ->join("om_shop b","a.uid = b.id","left")
                ->where([['a.id','eq',$value['product_id']]])
                ->group("b.type")
                ->value("b.type");
            $value['purchase_data'] = serializeMysql($value['purchase_data'],1);
            $value['purchase_data'] =array_values($value['purchase_data']);
            $value['cover_img'] =imgUrlToAbsolute($value['cover_img']);
        }
        return writeJson(200,$dataList);
    }

    /**
     * 查看订单状态
     * @param Request $request
     * @return \think\response\Json
     * @throws ParameterException
     */
    public function checkOrderStatus(Request $request){
         $post = $request->post();
         if(!isset($post['order_number'])){
             throw new ParameterException(['msg'=>'缺少订单号']);
         }
        if(strpos($post['order_number'],"POR")!==false){
            $status = (new ProductOrderRelation())->findOne([['order_number','eq',$post['order_number']]],"pay_status");//1是待支付 2是已支付
        }
        elseif(strpos($post['order_number'],"UMO")!==false){  //2   表示充值订单
            $status = (new UserMoneyOrder())->findOne([['order_number','eq',$post['order_number']]],"is_pay");//1是待支付 2是已支付
        }
        elseif(strpos($post['order_number'],"S")!==false){//3   商家支付订单
            $status = (new UserMoneyOrder())->findOne([['out_trade_no','eq',$post['order_number']]],"status");//1是待支付 2是已支付
        }else { //4  商城的子订单
            $status = (new \app\api\model\ProductOrder())->findOne([['order_number','eq',$post['order_number']]],"status");//0是待支付 1是已支付
            $status +=1;
        }
        return writeJson(200,['status'=>$status]);

    }
}